//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class BoundSheetRecord : WorkbookLevelRecord
    {
        public static BoundSheetRecord FromWorksheet (Worksheet worksheet)
        {
            //\\todo: visibility
            BoundSheetRecord result = new BoundSheetRecord {_name = (ShortXLUnicodeString) worksheet.Name, _sheetType = 0};
            return result;
        }
        private ShortXLUnicodeString _name;
        private byte _sheetType;
        private SheetState _visibility;
        private uint _streamPos;
        
        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.BoundSheet8; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
                context.SheetToPosition.Add(this, context.Position);
            context.Writer.Write(_streamPos);

            context.Writer.Write((byte)_visibility);
            context.Writer.Write((byte)_sheetType);
            _name.Write(context);

            //StringHelper.WriteString(_name, writer, StringLength.Byte, StringCompression.Latin);
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            context.Boundsheets.Enqueue(this);
            _streamPos = context.ReadUInt32();
            _visibility = (SheetState) context.ReadByte();
            _sheetType = context.ReadByte();
            _name.Read(context.Reader);
//            _name = StringHelper.ReadUtf8String(reader);
        }

        public override void Apply(BiffReaderWorkbookContext context)
        {
            context.BoundSheets.Add(this);
        }

        public void ApplyToSheet(Sheet ws, BiffReaderWorkbookContext context)
        {
            context.GetActions(ActionType.Sheet).Add(delegate
                                         {
                                             ws.SetName ((string)_name);
                                             ws.IsVisible = _visibility == SheetState.Visible;
                                         });
        }
    }
}